package com.blx.service.impl;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.StatusLine;
import org.apache.commons.httpclient.methods.MultipartPostMethod;
import org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.PartSource;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.blx.exception.UploadException;
import com.blx.service.UploadService;
import com.blx.utils.UUIDHexGenerator;

@Service
public class UploadServiceImpl implements UploadService {
	/**
	 * 属性交给调用方去注入
	 */
	private String fileServer;
	private String fileServerPort;
	private String fileServerUri;
	private static Logger logger = LoggerFactory.getLogger(UploadServiceImpl.class);

	/**
	 * 文件上传service
	 * @param fileBytes	文件字符流
	 * @param filename	文件名
	 * @param maxSize 最大上传  单位KB
	 * @return
	 * @throws Exception
	 * 
	 * update 20131210 解决传中文图片失败问题  方法：使用UUIDHexGenerator生成一个文件名 传入的文件名只用来做类型判断
	 */
	@SuppressWarnings("deprecation")
	public String uploadFile(byte[] fileBytes, String fName, int maxSize) throws UploadException {
		Assert.hasText(fName, "文件名为空");
		//获取文件类型
		String fileType = fName.substring(fName.lastIndexOf("."));
		Assert.hasText(fileType, "文件类型不明");
		
		String url = "";
		if(logger.isDebugEnabled()){
			logger.debug("pic server:"+fileServerUri);
		}
		//生成文件名
		String fileName = UUIDHexGenerator.getInstance().generate() + fileType;
		PartSource ps = new ByteArrayPartSource(fileName, fileBytes);
		
		HttpClient client = new HttpClient();
		client.getHostConfiguration().setHost(fileServer, Integer.valueOf(fileServerPort));
		MultipartPostMethod mpm = new MultipartPostMethod(fileServerUri);
		try {
			FilePart part = new FilePart("file1", ps);
			mpm.addPart(part);
			StringPart fileNamePart = new StringPart("fileName", fileName);
			mpm.addPart(fileNamePart);
			StringPart fileSizePart = new StringPart("maxSize", Integer.toString(maxSize));
			mpm.addPart(fileSizePart);
			mpm.setRequestHeader("accept", "application/json");

			client.executeMethod(mpm);
	
			int statusCode = -1;
			StatusLine sl = mpm.getStatusLine();
			if (sl != null) {
				statusCode = sl.getStatusCode();
			}
			if (statusCode != HttpStatus.SC_OK) {
				throw new UploadException("访问图片服务器错误，statusCode:" + statusCode);
			}
			JSONObject obj = new JSONObject(mpm.getResponseBodyAsString());
			//抛出文件上传异常类
			if (obj.has("error")) {
				throw new UploadException(obj.getJSONArray("error").getString(0).toString());
			}
			url = obj.getJSONArray(fileName).get(0).toString();
			
		} catch (Exception e) {
			logger.error("上传出现错误", e);
			throw new UploadException("上传出错", e);
		} finally {
			mpm.releaseConnection();
		}
		return url;

	}
	public String getFileServer() {
		return fileServer;
	}
	public void setFileServer(String fileServer) {
		this.fileServer = fileServer;
	}
	public String getFileServerPort() {
		return fileServerPort;
	}
	public void setFileServerPort(String fileServerPort) {
		this.fileServerPort = fileServerPort;
	}
	public String getFileServerUri() {
		return fileServerUri;
	}
	public void setFileServerUri(String fileServerUri) {
		this.fileServerUri = fileServerUri;
	}
}
